package com.hevs.samplewebapp.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

import com.google.appengine.api.datastore.Key;
import com.hevs.samplewebapp.server.entities.MedicalRecord;
import com.hevs.samplewebapp.server.entities.User;
import com.hevs.samplewebapp.server.json.ObjectMapperFactory;
import com.hevs.samplewebapp.server.service.MedicalRecordService;
import com.hevs.samplewebapp.server.service.UserService;

/**
 * 
 * @author Arnaud Durand creation : 20.03.12
 * 
 *         Goal: RESTful service for the Medical Records
 * 
 */

public class MedicalRecordServlet extends SessionAuthHttpServlet {

	public MedicalRecordServlet() {
		super(1);
	}
	
	public static UserService userService;
	{
		userService = new UserService();
	};


	public static final String queryMail = "usermail";
	private static final long serialVersionUID = 870866277965499216L;

	public static MedicalRecordService medicalRecordService;
	{
		medicalRecordService = new MedicalRecordService();
	};

	// security ok
	@Override
	protected void doSecureDelete(HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException {

		// ObjectMapper mapper = new ObjectMapper(); // can reuse, share
		// globall
		BufferedReader reader = req.getReader();
		StringBuilder sb = new StringBuilder();
		String line = reader.readLine();
		while (line != null) {
			sb.append(line + "\n");
			line = reader.readLine();
		}
		reader.close();
		System.out.println(sb.toString());

		ObjectMapper mapper = ObjectMapperFactory.get();
		MedicalRecord medicalRecord = mapper.readValue(sb.toString(),
				MedicalRecord.class);

		if (medicalRecord == null || medicalRecord.getKey() == null) {
			// bad request
			resp.sendError(400);
			return;
		}

		/*
		 * if (medicalData.getUser() != getAuthenticatedUser().getKey()) { //
		 * not authorized resp.sendError(403); return; }
		 */

		medicalRecordService.removeMedicalRecord(medicalRecord);

	}

	// security ok
	// add
	protected void doSecurePost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		HttpSession session = req.getSession(false);
		// ObjectMapper mapper = new ObjectMapper(); // can reuse, share
		// globall
		BufferedReader reader = req.getReader();
		StringBuilder sb = new StringBuilder();
		String line = reader.readLine();
		while (line != null) {
			sb.append(line + "\n");
			line = reader.readLine();
		}
		reader.close();
		System.out.println(sb.toString());

		ObjectMapper mapper = ObjectMapperFactory.get();
		List<MedicalRecord> medicalRecords = mapper.readValue(sb.toString(),
				new TypeReference<ArrayList<MedicalRecord>>() {
				});

		for (MedicalRecord medicalRecord : medicalRecords) {
			medicalRecord.setUser((Key) session.getAttribute("userKey"));
		}

		medicalRecordService.addMedicalRecords(medicalRecords);

	}

	// update
	protected void doSecurePut(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		HttpSession session = req.getSession(false);

		// ObjectMapper mapper = new ObjectMapper(); // can reuse, share
		// globall
		BufferedReader reader = req.getReader();
		StringBuilder sb = new StringBuilder();
		String line = reader.readLine();
		while (line != null) {
			sb.append(line + "\n");
			line = reader.readLine();
		}
		reader.close();
		System.out.println(sb.toString());

		ObjectMapper mapper = ObjectMapperFactory.get();
		MedicalRecord medicalRecord = mapper.readValue(sb.toString(),
				MedicalRecord.class);

		// throw Error 400
		if (medicalRecord == null) {
			resp.sendError(400);
			return;
		}

		/*
		 * if (medicalRecord.getUser() != getAuthenticatedUser().getKey()) { //
		 * not authorized resp.sendError(403); return; }
		 */

		// medicalData.setUser(getAuthenticatedUser().getKey());
		medicalRecord.setUser((Key) session.getAttribute("userKey"));

		medicalRecordService.updateMedicalRecord(medicalRecord);

	}

	protected void doSecureGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		HttpSession session = req.getSession(false);
		User user = new User();
		user.setKey((Key) session.getAttribute("userKey"));

		List<MedicalRecord> medicalRecords;

		medicalRecords = medicalRecordService.getAllMedicalRecords(user);
		// System.out.println(medicalRecordDAO.getAll(aimUser));

		ObjectMapper mapper = ObjectMapperFactory.get();

		resp.setContentType("application/json");
		PrintWriter writer = resp.getWriter();
		writer.write(mapper.writeValueAsString(medicalRecords));

		writer.flush();

	}

}
